from django.shortcuts import render
import datetime
# Create your views here.
from django.views import View
from .models import Area
from .models import House, HouseImage
from django.http import JsonResponse
from ihome.utils.views import LoginRequiredJsonMixin
import json
from django.db.models import Q
from django.core.paginator import Paginator,EmptyPage
from users.models import User
from order.models import Order
from ihome.settings import FDFS_BASE_URL
from ihome.libs.qiniuyun.qiniu_storage import storage



# 城区列表
class HouseListView(View):
    def get(self, request):
        area_name = Area.objects.all()
        area_list = []
        try:
            for areas in area_name:
                area_list.append({
                    'aid': areas.id,
                    'aname': areas.name
                })
        except Exception as e:
            return JsonResponse({'errno': 400, 'errmsg': '获取失败'})
        return JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': area_list})






class ReleaseHouseSearchListView(View):
    # 房屋数据搜索列表
    def get(self, request):
        aid = request.GET.get('aid')
        sd = request.GET.get('sd')
        ed = request.GET.get('ed')
        sk = request.GET.get('sk')
        p = request.GET.get('p', 1)

        if all([sd, ed]):
            # 将获得的字符串日期格式化为日期格式
            sd = datetime.datetime.strptime(sd, '%Y-%m-%d')
            ed = datetime.datetime.strptime(ed, '%Y-%m-%d')

        else:
            # 设置默认的 sd,ed
            sd = datetime.date.today()
            oneday = datetime.timedelta(days=1)
            # print(oneday)
            ed = sd + oneday

        #获取居住时间对象
        days = ed - sd
        #获取用户居住天数，整数类型
        days = days.days


        # 排序方式
        if sk == 'new':
            sort = '-create_time'
            # print(sort, type(sort))
        elif sk == 'booking':
            sort = '-order_count'
        elif sk == 'price_inc':
            sort = 'price'
        elif sk == 'price_des':
            sort = '-price'
        else:
            return JsonResponse({'errno': '4041', 'errmsg': '排序数据有错'})



        try:
            # 选出订单中 入住时间和离开时间 与用户所选时间 冲突的 订单
            orders = Order.objects.exclude(Q(end_date__lt=sd) | Q(begin_date__gt=ed))

            #选出用户指定的城区的所有房屋
            # 选出 用户入住天数 满足 房间的 最大入住天数  的房屋
            # 选出 未被预定的房屋 ,按照指定的顺序 排序
            house = House.objects.filter(area_id=aid).\
                exclude(min_days__gt=days).\
                filter(Q(max_days__gte=days) | Q(max_days = 0)).\
                exclude(id__in = [order.house_id for order in orders]).order_by(sort)

        except Exception as e:
            return JsonResponse({'errno': 4041, 'errmsg': '获取数据出错'})


            # 每页存储１个房屋信息
        paginator = Paginator(house, 2)

        try:
            # 获取当前页的房屋信息
            page_houses = paginator.page(p)
        except EmptyPage as e:
            return JsonResponse({'errno': 4041, 'errmsg': 'page数据错误'})

        # 获取房屋搜索数据的总页数
        total_page = paginator.num_pages

        houses = []
        area = Area.objects.get(pk=aid)
        for page_house in page_houses:
            houses.append({
                'address': page_house.address,
                'order_count': page_house.order_count,
                'title': page_house.title,
                'ctime': page_house.create_time,
                'price': page_house.price,
                'area_name': area.name,
                'room_count': page_house.room_count,
                'img_url': page_house.index_image_url.url,
                'user_avatar': User.objects.get(pk=page_house.user_id).avatar.url,
                'house_id':page_house.id
            })

        return JsonResponse({
            'errno': '0',
            'errmsg': 'ok',
            'data': {
                'houses': houses,
                'total_page':total_page
            }
        })

    #发布房源
    def post(self, request):
        dict = json.loads(request.body.decode())
        title = dict.get('title')
        price = dict.get('price')
        area_id = dict.get('area_id')
        address = dict.get('address')
        room_count = dict.get('room_count')
        acreage = dict.get('acreage')
        unit = dict.get('unit')
        capacity = dict.get('capacity')
        beds = dict.get('beds')
        deposit = dict.get('deposit')
        min_days = dict.get('min_days')
        max_days = dict.get('max_days')
        facility = dict.get('facility')
        area = Area.objects.get(id=area_id)
        # user = User.objects.get(username='loco')
        user = request.user
        if not all(
                [title, price, area_id, address, room_count, acreage, unit, capacity,
                 beds, deposit, min_days, max_days,
                 facility]):
            return JsonResponse({'errno': '4004', 'errmsg': '缺少必传参数'})

        house = House.objects.create(user=user,
                                     area=area,
                                     title=title,
                                     price=price,
                                     address=address,
                                     room_count=room_count,
                                     acreage=acreage,
                                     unit=unit,
                                     capacity=capacity,
                                     beds=beds,
                                     min_days=min_days,
                                     max_days=max_days,
                                     order_count=1,  # 预订完成的该房屋的订单数
                                     )
        house_id = house.id
        data = {}
        data['house_id'] = house_id
        house.facility.set(facility)
        house.save()




        return JsonResponse({'errno': '0', 'errmsg': '发布成功', 'data': data})



# 我的房屋列表
class MyhouseListView(LoginRequiredJsonMixin,View):
    def get(self, request):
        user = request.user
        house_list = []
        try:
            houses = House.objects.filter(user=user)
        except House.DoesNotExist:
            return JsonResponse({'errno': '4001', 'errmsg': '用户不存在'})
        for house in houses:

            image_url = house.index_image_url
            #未提取到房屋对应的图片地址
            if not image_url:
                image_url = ''
            else:
                image_url = image_url.url

            house_list.append({
                "address": house.address,
                "area_name": house.area_id,
                "ctime": house.create_time.strftime('%Y-%m-%d'),
                "house_id": house.id,
                "img_url": image_url,
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": user.avatar.url
            })
        data = {"houses": house_list}
        return JsonResponse({
            "data": data,
            "errno": "0",
            "errmsg": "ok"
        })

#上传房屋图片
class UploadHouseImageView(LoginRequiredJsonMixin, View):
    def post(self, request, house_id):
        #提取参数
        house_image = request.FILES.get('house_image')
        #参数校验
        if not house_image:
            return JsonResponse({'errno': 4103, 'errmsg': '缺少参数'})
        #业务逻辑处理

        house_image_url = storage(house_image.read())
            # url = FDFS_BASE_URL + house_image_url
        try:
            house = House.objects.get(id=house_id)
            house.index_image_url = house_image_url
            house.save()
        except Exception as e:
            return JsonResponse({'errno':4003,'errmsg':'数据写入失败'})

        try:
            HouseImage.objects.create(
                url = house_image_url,
                house=house
            )

        except Exception as e:
            return JsonResponse({'errno':4003,'errmsg':'数据写入失败'})

        #构建响应
        return JsonResponse({
            'data': {
                'url':house.index_image_url.url
            },
            'errno': '0',
            'errmsg': '图片上传成功！'
        })



# 房屋详情页
class HomeDetailsView(View):
    def get(self, request, house_id):
        # 提取参数
        user = request.user
        # 判断房屋是否存在
        if user.is_authenticated:
            user_id = user.id
        else:
            user_id = -1
        try:
            house = House.objects.get(id=house_id)
            house_user = User.objects.get(id=house.user_id)
        except Exception as e:
            return JsonResponse({'errno': 4001,
                                 'errmsg': '数据库查询错误'})
        #房屋的订单信息
        orders = house.order_set.all()
        #房屋的图片
        house_images = house.houseimage_set.all()
        #房屋的基础设施
        house_facility = house.facility.all()

        # 参数校验
        if not orders:
            comment = None
        else:
            comment = []

            for order in orders:

                comment.append({'comment': order.comment,
                               'ctime': order.update_time.strftime('%Y-%m-%d %H:%M:%S'),
                               'user_name': user.username})
        # 业务逻辑处理
        data = {"acreage": house.acreage,
                "address": house.address,
                "beds": house.beds,
                "capacity": house.capacity,
                "comments": comment,
                "deposit": house.deposit,
                "facilities": [
                    len(house_facility)
                ],
                "hid": house.id,
                "img_urls": [house_image.url.url for house_image in house_images],
                "max_days": house.max_days,
                "min_days": house.min_days,
                "price": house.price,
                'area_id':house.area_id,
                "room_count": house.room_count,
                "title": house.title,
                "unit": house.unit,
                "user_avatar": house_user.avatar.url,
                "user_id": house.user_id,
                "user_name": house_user.real_name
                }
        # 构建响应
        return JsonResponse(
            {'data': {
            'house': data,
            'user_id': user_id
        },
            'errno': 0,
            'errmsg': 'OK'
        })


#首页房屋推荐
class HotHouseView(View):
    def get(self, request):
        house = House.objects.all().order_by('-order_count')

        hot_house_queryset = house[:5]
        hot_house = []
        for houses in hot_house_queryset:
            hot_house.append({
                'house_id': houses.id,
                'title': houses.title,
                'img_url': houses.index_image_url.url,
            })

        return JsonResponse({
            'errno': 0,
            'errmsg': 'ok',
            'data': hot_house
        })

